package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    MemberMapper memberMapper;

    // 误报不用管
    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest loginInfo) {
        String userName = loginInfo.getUserName();
        String userPwd = loginInfo.getUserPwd();

        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", userName);
        List<Member> members = memberMapper.selectByExample(example);


        // 判断是否有用户被检索到，如果没有，说明用户名就有问题
        if(members.size() == 0){
            throw new ValidateException(
                    UserRetCode.USERORPASSWORD_ERRROR.getCode(), "用户名错误！");
        }

        // 到这不会出现数组越界的异常，直接取出
        Member existUserInfo = members.get(0);

        // 数据库中保存的应该是一个加密后的密码，这里我们取出后对比应该要有一个解密的操作
        // 但是因为spring自带的加密工具类没有解密，那我们将用户输入的密码加密后跟数据库的密码做对比
        String md5Password = DigestUtils.md5DigestAsHex(userPwd.getBytes());
        if(!existUserInfo.getPassword().equalsIgnoreCase(md5Password)){
            throw new ValidateException(
                    // 对应不上就抛出对应的异常
                    UserRetCode.USERORPASSWORD_ERRROR.getCode(), "密码错误！");
        }

        // 判断是否激活
        if(existUserInfo.getIsVerified().equals("N")){
            throw new ValidateException(UserRetCode.USER_ISVERFIED_ERROR.getCode(),
                    UserRetCode.USER_ISVERFIED_ERROR.getMessage());
        }

        // 将member对象转换成UserLoginResponse并且返回
        UserLoginResponse userLoginResponse = userConverterMapper.converter(existUserInfo);
        return userLoginResponse;
    }
}
